package com.definity.toolkit.web.taglib;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

public class FormTag extends BaseTag {

	private static final long serialVersionUID = 8039288267971880927L;

	private String action;
	private String method;
	private String domain;
	private String enctype;

	private Class<?> domainType;
	private String referenceName;

	private Object value;
	
	public FormTag() {
		setMethod("post");
		setI18n("form");
	}
	
	public void setAction(String action) {
		this.action = action;
	}
	
	public void setMethod(String method) {
		this.method = method;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}

	public void setEnctype(String enctype) {
		this.enctype = enctype;
	}
	
	public void setValue(Object value) {
		this.value = value;
	}
	
	public Class<?> getDomainType() throws JspException {
		if (domainType != null && domainType.getName().equals(domain))
			return domainType; 
		
		try {
			domainType = Class.forName(domain);
			return domainType;
		} catch (ClassNotFoundException e) {
			throw new JspException(e);
		} 
	}

	public String getDomainReferenceName() throws JspException {
		Class<?> domainType = getDomainType();

		if (referenceName != null && referenceName.equalsIgnoreCase(domainType.getSimpleName()))
			return referenceName;
		
		referenceName = domainType.getSimpleName();
		referenceName = Character.toLowerCase(referenceName.charAt(0)) + referenceName.substring(1);
		
		return referenceName;
	}

	public String getDomainInstanceName() throws JspException {
		return getDomainReferenceName();
	}
	
	public Object getDomainInstanceValue(String attribute) throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		
		Object domainInstance = value;
		if (domainInstance == null)
			domainInstance = request.getAttribute(getDomainInstanceName());
		
		return getValue(domainInstance, attribute);
	}
	
	@Override
	public int doStartTag() throws JspException {
		String referenceName = getDomainReferenceName();
		
		StringBuilder html = new StringBuilder();
		html.append("\n<form action=\"" + action + "\"");
		html.append(" method=\"" + method + "\"");
		if (enctype != null && enctype.trim().length() != 0)
			html.append(" enctype=\"" + enctype + "\"");
		html.append(createStyleClass());
		html.append(">");
		html.append("\n<input type=\"hidden\" id=\"" + referenceName + ".id\" name=\"" + referenceName + ".id\" value=\"" + valueToString(getDomainInstanceValue("id")) + "\" />");
		
		write(html);
		
		return EVAL_BODY_AGAIN;
	}

	@Override
	public int doEndTag() throws JspException {
		StringBuilder html = new StringBuilder();
		html.append("\n</form>");
		
		write(html);
		
		return EVAL_PAGE;
	}

}
